package handler

import (
	"context"
	"lab-service/post/model"
	pn "lab-service/proto/notice"
)

type Notice struct{}

func (m *Notice) One(ctx context.Context, req *pn.NoticeRequest, rsp *pn.NoticeResponse) error {
	// model Notice -> mn
	mn := &model.Notice{
		Id: req.Id,
	}

	if err := mn.OneById(); err != nil {
		return err
	}

	rsp.Notice = &pn.OneNotice{
		Id:        mn.Id,
		Enable:    mn.Enable,
		CreatedAt: mn.CreatedAt.Unix(),
		Title:     mn.Title,
		Content:   mn.Content,
		Pics:      mn.Pics,
	}

	return nil
}

func (m *Notice) Page(ctx context.Context, req *pn.NoticeRequest, rsp *pn.NoticeResponse) error {
	// model Notice -> mn
	mn := &model.Notice{
		Enable: req.Enable,
	}

	ns, err := mn.Page(req.PageNum, req.PageSize, req.Desc, req.Order)
	if err != nil {
		return err
	}

	for _, n := range ns {
		rsp.Notices = append(rsp.Notices, &pn.OneNotice{
			Id:        n.Id,
			CreatedAt: n.CreatedAt.Unix(),
			Title:     n.Title,
			Enable:    n.Enable,
			//Content:   n.Content,
			//Pics:      n.Pics,
		})
	}

	rsp.Total, err = mn.Count()
	if err != nil {
		return err
	}

	rsp.PageSize = req.PageSize
	rsp.PageNum = req.PageNum

	return nil
}

func (m *Notice) Create(ctx context.Context, req *pn.NoticeRequest, rsp *pn.NoticeResponse) error {
	// model Notice -> mm
	mm := &model.Notice{
		Title:   req.Title,
		Content: req.Content,
		Enable:  true,
		Pics:    req.Pics,
	}

	if err := mm.Create(); err != nil {
		return err
	}

	return nil
}

func (m *Notice) Toggle(ctx context.Context, req *pn.NoticeRequest, rsp *pn.NoticeResponse) error {
	// model Notice -> mn
	mn := &model.Notice{
		Id: req.Id,
	}

	if err := mn.OneById(); err != nil {
		return err
	}

	if err := mn.Toggle(); err != nil {
		return err
	}

	return nil
}
